package com.webull.information.center.carwler.task;

import com.webull.information.center.carwler.common.model.StockTitle;
import com.webull.information.center.carwler.task.handler.StockGoogleNewsHandler;
import com.webull.securities.client.model.Fund;
import com.webull.securities.client.model.parm.FundNewsParam;
import com.webull.securities.client.service.ExchangeService;
import com.webull.securities.client.service.FundService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

@Component
public class News_GoogleFull_EtfFund_Task {

    protected final Logger logger = LogManager.getLogger(getClass());

    private @Autowired
    FundService fundService;

    private @Autowired
    ExchangeService exchangeService;

    private @Autowired
    StockGoogleNewsHandler stockGoogleNewsHandler;

    private final Integer pageSize = 100;

    public Integer fullEtfFundGoogleNewsRegion(Integer regionId, Integer lastId) {
        logger.info("News_GoogleFull_EtfFund_Task.fullEtfFundGoogleNewsRegion start exchangeCode:{},lastId:{},loop:{}", regionId, lastId);
        full:
        do {
            FundNewsParam param = new FundNewsParam();
            param.setRegionId(regionId);
            param.setSpecialType(Fund.SpecialTypeConstants.ETFFUND);
            List<Fund> res = fundService.queryPagingByParm(param, lastId, pageSize);
            if (res == null || res.isEmpty()) {
                lastId = null;
                break full;
            }
            logger.info("News_GoogleFull_EtfFund_Task.News_GoogleFull_EtfFund_TaskExchangeCode stocks:" + res.size());
            lastId = res.get(res.size() - 1).getTickerId();
            procss(res);
        } while (true);

        return lastId;
    }

    private void procss(List<Fund> res) {

        if (res == null) {
            return;
        }
        for (Fund s : res) {
            try {
                StockTitle stockTitle = new StockTitle();
                BeanUtils.copyProperties(s, stockTitle);
                Optional.ofNullable(exchangeService.getById(s.getExchangeId()))//
                        .ifPresent(v -> {
                            stockTitle.setExchangeAlias(v.getAlias());
                            stockTitle.setExchangeCode(v.getExchangeCode());
                            stockGoogleNewsHandler.handlerByStockTitle4Google(stockTitle);
                            logger.info("News_GoogleFull_EtfFund_Task.procss stockTitle:" + stockTitle);
                        });
            } catch (Exception e) {
                logger.error("News_GoogleFull_EtfFund_TaskTask 全量新闻任务失败", e);
            }
        }
        logger.info("News_GoogleFull_EtfFund_TaskTask procss end:" + res.size());

    }
}
